package com.example.netty.handler;

import com.example.netty.callback.SampleLongConnectEventCallback;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.handler.timeout.IdleStateEvent;

/**
 * @Auther Created by l.wang on 2019/5/29.
 */
public class SampleLongConnectNettyHandler  extends SimpleChannelInboundHandler<String> {

    private SampleLongConnectEventCallback sampleLongConnectEventCallback;

    public SampleLongConnectNettyHandler(SampleLongConnectEventCallback sampleLongConnectEventCallback) {
        this.sampleLongConnectEventCallback = sampleLongConnectEventCallback;
    }

    @Override
    public void channelActive(ChannelHandlerContext channelHandlerContext) throws Exception {
        sampleLongConnectEventCallback.onConnectionCreated(channelHandlerContext);
    }

    @Override
    public void userEventTriggered(ChannelHandlerContext channelHandlerContext, Object evt) throws Exception {
        if (IdleStateEvent.class.isAssignableFrom(evt.getClass())) {
            IdleStateEvent event = (IdleStateEvent) evt;
            sampleLongConnectEventCallback.onConnectionIdle(event.state(), channelHandlerContext);
        }
    }

    @Override
    public void channelInactive(ChannelHandlerContext channelHandlerContext) throws Exception {
        sampleLongConnectEventCallback.onConnectionClosed(channelHandlerContext);
    }

    @Override
    @SuppressWarnings("unchecked")
    protected void channelRead0(ChannelHandlerContext channelHandlerContext, String msg) throws Exception {
        if (msg != null) {
            sampleLongConnectEventCallback.onRead(channelHandlerContext, msg);
        }
    }


    @Override
    public void exceptionCaught(ChannelHandlerContext channelHandlerContext, Throwable cause) throws Exception {
        cause.printStackTrace();
        channelHandlerContext.close();
    }
}
